package de.koller.altitude.engine.world;

import de.koller.aframe.gl.AVertexBuffer;
import de.koller.aframe.util.physics.Size;
import de.koller.altitude.Altitude;
import de.koller.altitude.render.obj.IVisualObject;
import de.koller.oceanFramework.util.ColorIntUtil;
import org.lwjgl.opengl.GL11;

public class Floor implements IVisualObject {
	
	private final int floorSize = 15;
	private final float floorRatio = 2;
	private AVertexBuffer vbo;
	public final Size size = new Size();
	
	private final FloorTile[][] tiles = new FloorTile[ floorSize ][ (int)(floorSize*floorRatio) ];
	
	public Floor() {
		size.size.set( floorSize, 0, (int)(floorSize*floorRatio) );
	}
	
	public void setColor( int tx, int tz, int c ) {
		tiles[tx][tz].setColorAtEdge( 0, c );
		tiles[tx][tz-1].setColorAtEdge( 1, c );
		tiles[tx-1][tz-1].setColorAtEdge( 2, c );
		tiles[tx-1][tz].setColorAtEdge( 3, c );
	}
	
	private void initGrid() { 
		float[] vbod = new float[ floorSize*(int)(floorSize*floorRatio)*FloorTile.vboSize ];
		
		for( int x = 0; x < tiles.length; x++ )
			for( int z = 0; z < tiles[0].length; z++ ) {
				tiles[x][z] = new FloorTile( x, z, 
						(z * tiles.length + x) * FloorTile.vboSize);
				tiles[x][z].setVBO( vbod );
			}
				
		
		vbo = AVertexBuffer.create( AVertexBuffer.UsageType.Dynamic, GL11.GL_QUADS );
		vbo.setup( 3, 3, 0, 2 );
		vbo.setData( vbod );
		
//		setColor( 10, 10, 0xffff0000 );
//		setColor( 11, 10, 0xff00ff00 );
//		setColor( 11, 11, 0xff0000ff );
	}
	
	@Override
	public void renderThis() {
		if( vbo == null )
			initGrid();
		
		Altitude.texture().grid.bindAnisotrophic();
		vbo.renderThis();
	}
	
	private class FloorTile {
		public static final int vboSize = (3 + 3 + 2)*4;
		
		public final float x, z;
		private final int offset;
		
		public FloorTile( int x, int z, int offset ) {
			this.x = x;
			this.z = z;
			this.offset = offset;
		}
		
		public void setColorAtEdge( int e, int color ) {
				 if( e == 0 ) setColor( color, offset+3 );
			else if( e == 1 ) setColor( color, offset+11 );
			else if( e == 2 ) setColor( color, offset+19 );
			else if( e == 3 ) setColor( color, offset+27 );
		}
		
		private void setColor( int c, int offset ) {
			vbo.changeData( offset,
				ColorIntUtil.getRValueF( c ),
				ColorIntUtil.getGValueF( c ),
				ColorIntUtil.getBValueF( c )
			);
		}
		
		public void setVBO( float... a ) {
			int i = offset;
			a[i+0] = x; a[i+1] = 0; a[i+2] = z;
			a[i+3] = 1;
			a[i+4] = 1;
			a[i+5] = 1;
			a[i+6] = 0; a[i+7] = 0;
			
			a[i+8] = x; a[i+9] = 0; a[i+10] = z+1;
			a[i+11] = 1;
			a[i+12] = 1;
			a[i+13] = 1;
			a[i+14] = 0; a[i+15] = 1;
			
			a[i+16] = x+1; a[i+17] = 0; a[i+18] = z+1;
			a[i+19] = 1;
			a[i+20] = 1;
			a[i+21] = 1;
			a[i+22] = 1; a[i+23] = 1;
			
			a[i+24] = x+1; a[i+25] = 0; a[i+26] = z;
			a[i+27] = 1;
			a[i+28] = 1;
			a[i+29] = 1;
			a[i+30] = 1; a[i+31] = 0;
		}
		
	}
	
}
